import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/mode/master/file_loxen.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/collection_file_add_viewmodel.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';

// ignore: must_be_immutable
class CollectionFileWidget extends StatelessWidget {
  final FileType fileType;
  final String id;
  CollectionFileAddViewModel model;
  ScrollController scrollController;

  CollectionFileWidget({Key key, this.fileType, this.id}) : super(key: key) {
    model = CollectionFileAddViewModel(fileType);
    model.loadData();
    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        model.nextData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<CollectionFileAddViewModel>.value(
      value: model,
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Row(
                children: <Widget>[
                  MySubassembly.getBackIcon(context, color: Colors.black),
                  Expanded(
                    flex: 4,
                    child: Center(
                      child: Text(
                        getName(),
                        style: TextStyle(
                            fontSize: 32.sp,
                            color: Theme.of(context).textTheme.subtitle2.color),
                      ),
                    ),
                  ),
                  MySubassembly.getSearchIcon(() {
                    createFile(context);
                  }, url: 'images/create@2x.png')
                ],
              ),
            ),
          ),
        ),
        body: Builder(builder: (context) {
          BaseState state =
              context.select<CollectionFileAddViewModel, BaseState>(
                  (value) => value.mState);
          if (state == BaseState.CONTENT) {
            return Container(
              color: Theme.of(context).backgroundColor,
              child: Column(
                children: <Widget>[
                  Expanded(child: Builder(builder: (context) {
                    var list = context.select<CollectionFileAddViewModel,
                        List<FileLoxen>>((value) => value.list);
                    return Container(
                      margin:
                          EdgeInsets.only(top: 50.h, left: 35.w, right: 35.w),
                      child: GridView.count(
                        controller: scrollController,
                        crossAxisCount: 3,
                        mainAxisSpacing: 20.w,
                        crossAxisSpacing: 20.w,
                        childAspectRatio: 0.75,
                        children: list
                            .map((entity) => _fileItem(context, entity))
                            .toList(),
                      ),
                    );
                  })),
                  InkWell(
                    onTap: () {
                      model.collection(id, onSuccess: () {
                        Navigator.of(context).pop(true);
                      });
                    },
                    child: Container(
                      width: double.infinity,
                      height: 88.h,
                      color: Theme.of(context).primaryColor,
                      child: Center(
                        child: Text(
                          StringResources.wan_cheng,
                          style: TextStyle(
                              fontSize: 35.sp,
                              color:
                                  Theme.of(context).textTheme.subtitle1.color),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            );
          }
          if (state == BaseState.FAIL) {
            return FailWidget(
                onClick: () =>
                    context.read<CollectionFileAddViewModel>().loadData());
          }
          if (state == BaseState.EMPTY) {
            return EmptyWidget();
          }
          if (state == BaseState.LOADING) {
            return LoadingWidget();
          }
          return Text('');
        }),
      ),
    );
  }

  Widget _fileItem(BuildContext context, FileLoxen entity) {
    return GestureDetector(
      onTap: () {
        context.read<CollectionFileAddViewModel>().changeSelect(entity);
      },
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Stack(
            children: <Widget>[
              Container(
                width: double.infinity,
                height: double.infinity,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(15.w),
                    child: entity.cover != ''
                        ? CachedNetworkImage(
                            imageUrl:  ImageUrlUtil.getClean(entity.cover),
                            placeholder: (_, __) => Constants.loadingIcon(),
                            fit: BoxFit.cover,
                          )
                        : Center(
                            child: Image.asset(
                              'images/default_folder.png',
                              width: 57.w,
                              height: 49.w,
                            ),
                          )),
                decoration: BoxDecoration(
                    color: Color(0xFF0CB7D9),
                    borderRadius: BorderRadius.all(Radius.circular(15.w))),
              ),
              entity.isHide
                  ? AbsorbPointer(
                      child: Container(
                        width: double.infinity,
                        height: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.white.withAlpha(76),
                          borderRadius: BorderRadius.circular(15.w),
                        ),
                        child: Center(
                          child: Image.asset(
                            'images/icon_privacy.png',
                            width: 58.w,
                            height: 58.w,
                          ),
                        ),
                      ),
                    )
                  : Constants.empty
            ],
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              height: 75.h,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.black.withAlpha(30),
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(15.w),
                  bottomRight: Radius.circular(15.w),
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.only(left: 25.w),
                    child: Text(
                      entity.name,
                      style: TextStyle(
                          fontSize: 22.sp,
                          color: Theme.of(context).textTheme.subtitle1.color,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 25.w),
                    width: double.infinity,
                    child: Text(
                      '${entity.num}${getName()}',
                      style: TextStyle(fontSize: 18.sp, color: Colors.white),
                    ),
                  )
                ],
              ),
            ),
          ),
          Align(
            alignment: Alignment.bottomRight,
            child: Padding(
              padding: EdgeInsets.only(right: 15.w, bottom: 15.w),
              child: Builder(builder: (context) {
                bool select = context.select<CollectionFileAddViewModel, bool>(
                    (value) => entity.select == 1);
                return select
                    ? Image.asset(
                        'images/selected@2x.png',
                        width: 30.w,
                        height: 30.w,
                      )
                    : Constants.empty;
              }),
            ),
          )
        ],
      ),
    );
  }

  String getName() {
    String name;
    if (fileType == FileType.INSPIRATION) {
      name = StringResources.ling_gan;
    } else if (fileType == FileType.MATERIAL) {
      name = StringResources.su_cai;
    } else if (fileType == FileType.IMAGE) {
      name = StringResources.cai_ji;
    } else if (fileType == FileType.KNOWLEDGE) {
      name = StringResources.zhi_shi;
    } else {
      name = StringResources.ying_yong;
    }
    return name;
  }

  void createFile(BuildContext context) {
    showDialog<String>(
        context: context,
        builder: (context) {
          return DialogUtil.getCreateFileDialog(context,
              onCreate: (select, text) {
            if (text != null && text.trim() != '') {
              model.createFile(text, !select);
            }
          });
        });
  }
}
